import json
import requests
import datetime
import pytest

pro_type = {1: 'UNIT', 2: 'AMOUNT', 3: 'QUANTITY', 4: 'PWP', 5: 'MATCH', 6: 'REDEEM', 7: 'BRAND', 8: 'CATE',
            9: 'BASKET', 10: 'SPECIAL_IDENTITY', 11: 'PAYMENT', 12: 'PAYMENT_FREEBIE', 13: '收银台赠品活动'}


class ProInfo:
    def __init__(self, address):
        self.address = address

    def pro_list_query_by_proid(self, ticket, pro_id):
        url = '{}/instance/page'.format(self.address)
        header = {"Cookie": "ticket={}".format(ticket), "Content-Type": "text/plain"}
        # print(header)
        data = {"proId": pro_id, "currentPage": 1, "pageSize": 10}
        data = json.dumps(data)
        res = requests.post(url, data=data, headers=header)
        res_code = res.json()['code']
        # print(res.text)
        if res_code == '0000':
            res_data = res.json()['data']
        print(res_data)
        return res_data

    def pro_view(self, ticket, pro_id):
        """调用来客查询促销详情接口，返回促销相关信息"""
        url = '{}/instance/info/{}'.format(self.address, pro_id)
        header = {"Cookie": "ticket={}".format(ticket)}
        # print(header)
        # print(url)
        res = requests.get(url, headers=header)
        # print(res.encoding)
        res_code = res.json()['code']
        # print(res.text.encode("ISO-8859-1").decode('utf8'))
        if res_code == '0000':
            res_data = json.loads(res.text)['data']
            # print('--------------------')
        else:
            raise Exception('调用url返回错误：{}'.format(res.text))
        # 处理一下促销类型
        res_data['baseInfo']['proType'] = pro_type[res_data['baseInfo']['proType']]
        print('查询到的促销详情为：', res_data)
        return res_data

    def pro_copy(self, ticket, pro_id):
        """先调用查询促销详情接口，获取促销内容，然后创建一个配置项一样的促销"""
        pro_info = self.pro_view(ticket, pro_id)
        url = '{}/instance/save'.format(self.address, pro_id)
        header = {"Cookie": "ticket={}".format(ticket), "Content-Type": "text/plain"}
        # print(header)
        # print(url)
        # 处理一下促销类型
        for k, v in pro_type.items():
            if pro_info['baseInfo']['proType'] == v:
                pro_info['baseInfo']['proType'] = k
                break
        # 为了避免复制之前的促销是已过期的。所以重新设置促销时间
        proStartTime = datetime.datetime.now().strftime("%Y-%m-%d") + ' 00:00:00'
        proEndTime = (datetime.datetime.now() + datetime.timedelta(days=360)).strftime("%Y-%m-%d") + ' 00:00:00'
        # 处理joinItem，适应全部商品
        joinItem = pro_info.get('joinItem', None)
        if joinItem:
            items = joinItem.get('singleItems')[0].get('items')
            if items == [{}]:
                joinItem['singleItems'][0]['items'] = None
        # 构建入参
        data = {
            "barCode": pro_info.get('barCode', None),
            "baseInfo": pro_info.get('baseInfo', None),
            "blackList": pro_info.get('blackList', None),
            "channel": pro_info.get('channel', None),
            "excludeItems": pro_info.get('excludeItems', []),
            "expenseRules": pro_info.get('expenseRules', []),
            "joinExecutor": pro_info.get('joinExecutor', None),
            "joinItem": pro_info.get('joinItem', None),
            "member": pro_info.get('member', None),
            "printing": pro_info.get('printing', None),
            "rule": pro_info.get('rule', None),
            "suitTriggers": pro_info.get('suitTriggers', []),
            "suitReward": pro_info.get('suitReward', None),  # 组合促销必填
            "time": {
                "dateType": pro_info['time'].get('dateType', 0),
                "execTimes": pro_info['time'].get('execTimes', []),
                "proEndTime": proEndTime,
                "proStartTime": proStartTime
            },
            "venderBaseInfo": pro_info.get('venderBaseInfo', None),
            "cashierRule": pro_info.get('cashierRule', None),
            "showInfo": pro_info.get('showInfo', None)
        }
        # 如果是整单促销，不需要促销商品joinItem
        if pro_info.get('baseInfo').get('proType') == 9:
            data['joinItem'] = None
        data = json.dumps(data)
        print('复制促销入参为：', data)
        res = requests.post(url, data=data, headers=header)
        res_code = res.json()['code']
        if res_code == '0000':
            pro_id_copy = json.loads(res.text)['data']
            print('促销复制成功，原促销id为：{}，复制后促销id为：{}'.format(pro_id, pro_id_copy))
        else:
            pro_id_copy = None
            print('促销复制失败，促销id为：{}，报错信息为：{}'.format(pro_id, res.text))
            pytest.assume(False, '处理的促销id：{}，调用url返回错误：{}'.format(pro_id, res.text))
        return pro_id_copy

    # def pro_status_not_4(self, ticket, db_info, pro_ids):
    #     """传入促销id列表，返回不为促销中的数据，如果为已结束或强制结束就重新新建促销"""
    #     mysql_query = MysqlQuery(db_info)
    #     pros = mysql_query.pro_status_view(pro_ids)
    #     pro_ids_copy = {}
    #     pro_copy_fail = []
    #     for pro_id, status in pros.items():
    #         if status in (5, 7):
    #             pro_id_copy = self.pro_copy(ticket, pro_id)
    #             if pro_id_copy is not None:
    #                 pro_ids_copy[pro_id] = pro_id_copy
    #             else:
    #                 pro_copy_fail.append(pro_id)
    #         elif status == 3:
    #             print('部分促销状态为审核通过，如：{}，需要等待其变更为促销中！！'.format(pro_id))
    #             pro_ids_copy[pro_id] = pro_id
    #         elif status == 4:
    #             pass
    #         else:
    #             pytest.assume(False, '处理的促销id：{}，查询到的促销状态为：{}。理论上不应该，不合理，检查一下吧~~~~~'.format(pro_id, status))
    #     if pro_copy_fail:
    #         print('复制失败的促销列表：{}'.format(pro_copy_fail))
    #     if pro_ids_copy:
    #         pass
    #     else:
    #         print('所有促销状态正常，没有需要重新创建的数据！')
    #     mysql_query.mydb.close()
    #     return pro_ids_copy

    def pro_status_not_4(self, ticket, db_info, pro_ids):
        """传入促销id列表，返回不为促销中的数据，如果为已结束或强制结束就重新新建促销"""
        pro_ids_copy = {}
        for ids in pro_ids:
            pro_ids_copy[ids] = 4
        # mysql_query = MysqlQuery(db_info)
        # pros = mysql_query.pro_status_view(pro_ids)
        pros = {}
        res = []
        for ids in pro_ids:
            res.append((ids, 4))
        for re in res:
            pros[re[0]] = re[1]
        # pro_ids_copy = {}
        pro_copy_fail = []
        for pro_id, status in pros.items():
            if status in (5, 7):
                pro_id_copy = self.pro_copy(ticket, pro_id)
                if pro_id_copy is not None:
                    pro_ids_copy[pro_id] = pro_id_copy
                else:
                    pro_copy_fail.append(pro_id)
            elif status == 3:
                print('部分促销状态为审核通过，如：{}，需要等待其变更为促销中！！'.format(pro_id))
                pro_ids_copy[pro_id] = pro_id
            elif status == 4:
                pass
            else:
                pytest.assume(False, '处理的促销id：{}，查询到的促销状态为：{}。理论上不应该，不合理，检查一下吧~~~~~'.format(pro_id, status))
        if pro_copy_fail:
            print('复制失败的促销列表：{}'.format(pro_copy_fail))
        if pro_ids_copy:
            pass
        else:
            print('所有促销状态正常，没有需要重新创建的数据！')
        # mysql_query.mydb.close()
        return pro_ids_copy


if __name__ == '__main__':
    proInfo = ProInfo('http://dfdevtestrta-promotion-partner.dmall.com.hk')
    ticket = '3EE28BCBA0D879D0674ED7CBC3BE2908C0A04664A2A8F49876953B183016BA59DD8285C33C41ACCD25875E3284FD87E7105F668B22053837143D8B2FF1D06A13AC0F8FC41E82CC4CF8E3BA10FAA745F18A3385CD7AF38687DE56FC5378D3E9D700850B22C4C9812F7A9CE69928B424BAC17BFA655DA86DE1BF72DCF472D2B33E'
    # res_data = proInfo.pro_view(ticket, 2021062500000010)
    # print(res_data)
    # db = {'host': '10.16.247.211', 'port': 8701, 'username': 'admin_test', 'password': 'admin_test@2019!pass'}
    # proInfo.pro_status_not_4(ticket, db, [2021070200000030])
    # pros_copy = proInfoMysql.pro_status_view([2021070200000030])
    # pros_copy = proInfoMysql.pro_status_view([2021070800000001])
    aa = {}
    for i in [2021071700000006, 2021071700000007, 2021071700000012, 2021071700000009, 2021080300000007, 2021080300000008, 2021080300000009, 2021080300000011, 2021080300000012, 2021080300000013, 2021080300000014, 2021080300000016, 2021080300000017, 2021080300000018, 2021080300000019, 2021080300000020, 2021080300000021, 2021080300000024, 2021080300000025, 2021080300000026, 2021080300000027, 2021080300000028, 2021080300000029, 2021080300000030, 2021080300000031, 2021080300000032, 2021080300000033, 2021080300000034, 2021080300000035, 2021080300000036, 2021080300000037, 2021080300000038, 2021080300000039, 2021080300000040, 2021080300000041, 2021080300000042, 2021080300000043, 2021080300000044, 2021080300000045, 2021080300000047, 2021080300000048, 2021080300000049, 2021080300000050, 2021080300000051, 2021080300000052, 2021080300000053, 2021080300000058, 2021080300000055, 2021080300000056, 2021080300000057, 2021080300000059, 2021080300000060, 2021080300000061, 2021080300000062, 2021080300000063, 2021080300000064, 2021080300000065, 2021080300000066, 2021080300000067, 2021080300000068, 2021080300000069, 2021080300000070]:
        res_data = proInfo.pro_view(ticket, i)
        aa[i] = res_data['baseInfo']['proName']
    print(aa)



